import { login, logout, getInfo } from '@/api/user'
import {
  getToken,
  setToken,
  removeToken,
  getUserInfo,
  setUserInfo,
  removePreview
} from '@/utils/auth'
import {
  getCurrentUser
} from '@/api/common'
import router, { resetRouter } from '@/router'
import profile from '@/assets/profile.gif'

const state = {
  token: getToken(),
  info: getUserInfo(),
  name: getUserInfo().name,
  avatar: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    setToken(token)
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_INFO: (state, info) => {
    setUserInfo(info)
    state.info = JSON.parse(info)
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const {
      username,
      password,
      captcha
    } = userInfo
    return new Promise((resolve, reject) => {
      login({
        uid: username.trim(),
        pwd: password,
        vcode: captcha || undefined
      }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        commit('SET_NAME', data.name)
        commit('SET_INFO', JSON.stringify(data))
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getCurrentUser().then(response => {
        const {
          data
        } = response
        commit('SET_NAME', data.name)
        commit('SET_INFO', JSON.stringify(data))
        resolve()
      })
      commit('SET_ROLES', ['admin'])
      commit('SET_AVATAR', profile)
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resetRouter()
      removePreview()
      dispatch('tagsView/delAllViews', null, {
        root: true
      })
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
